package com.youseu.taoliving.commodity.exception;

import com.youseu.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tao
 * @version 1.0
 * 全局异常处理器
 */
@RestControllerAdvice(basePackages = "com.youseu.taoliving.commodity.entity")
public class GlobalExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)//处理数据校验异常
    public R handleVaildException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            map.put(field,message);
        }
        // return R.error(400,"数据非法").put("data",map);
        return R.error(ErrorCodeEnum.INVALID_EXCEPTION.getCode(),
                ErrorCodeEnum.INVALID_EXCEPTION.getMessage())
                .put("data",map);
    }

    @ExceptionHandler(Throwable.class)//处理其他异常
    public R handleException(Exception exception){
        return R.error(ErrorCodeEnum.UNKNOWN_EXCEPTION.getCode(),
                ErrorCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
